package com.synjones.beijing.controls
{
	import mx.rpc.events.FaultEvent;
    import mx.controls.ComboBox;
    import mx.collections.*;
    import mx.rpc.AbstractService;
    import mx.rpc.AsyncToken;
    import mx.rpc.events.ResultEvent;
    import mx.utils.ArrayUtil;
	import com.synjones.beijing.*;
	import mx.controls.Alert;
	import flash.events.Event;
	import com.synjones.beijing.model.IO_DEPTS_Model;
	
	import com.synjones.beijing.model.IO_DEPTS_Model;

	public class ComboBoxDept extends ComboBox
	{
		public function ComboBoxDept()
		{
			super();
		}
		
		[Bindable]
	    private var _dataProvider:ArrayCollection;
	    
	    public var term:String = "200609";
	    public var sysname:String = "注册";
		public var deptLevel:int = 1;
		[Bindable]
		public var parentDeptCode:String = "";
		public var parentDeptControl:ComboBoxDept;
	    
    	private var service:AbstractService;
    	
    	public function Init() : void{
    		if(this.parentDeptControl == null){
				parentDeptCode = "";				
    		}else{
    			
    			if(parentDeptCode == parentDeptControl.parentDeptCode){ //如果爸爸选择的是全部
    				_dataProvider = new ArrayCollection();
    				var temp:IO_DEPTS_Model = new IO_DEPTS_Model();			
					temp.DEPTNAME = "全部";			
					temp.DEPTCODE = parentDeptCode;
					temp.DeptFullName = "全部";
		    	    _dataProvider.addItemAt(temp,0);
		    	    this.dispatchEvent(new Event("change")); 
    			}else{
    				parentDeptCode = parentDeptControl.parentDeptCode;    				
    			}
    			if(deptLevel != 1) return;
    			service = ServiceLocator.getRestaurantService();
	    		var token: AsyncToken = AsyncToken(service.GetDepartments(deptLevel,sysname,term,parentDeptCode));
	            token.addResponder(new TokenResponder(getResult, "获取部门信息失败"));
    		}
    		
    	}
    	private function getResult(event:ResultEvent):void{ 
    	    _dataProvider = event.result as ArrayCollection;			
//	    	    if(this.deptLevel != 1){
				var temp:IO_DEPTS_Model = new IO_DEPTS_Model();			
				temp.DEPTNAME = "全部";			
				temp.DEPTCODE = parentDeptCode;
				temp.DeptFullName = "全部";
	    	    _dataProvider.addItemAt(temp,0);
//    	    }
    	    this.dataProvider = _dataProvider;    
    	    this.labelField = "DEPTNAME";         
    	    this.dispatchEvent(new Event("change"));
        }
        
        public function set selectedDept(code:String):void{
            var i:int = 0;
            for(i=0;i<_dataProvider.length;i++)
            {
                if(_dataProvider[i].DEPTCODE == code)
                {
                    this.selectedIndex = i;
                    return;
                }
            }
            this.selectedIndex = 0;
        }
        [Bindable("change")]
    	[Bindable("collectionChange")]
        [Bindable("valueCommit")]
        public function get selectedDept():String{
            return this.selectedItem.DEPTCODE;
        }
		
	}
}